package com.iplant.ams.controller.dms.scada;

import com.iplant.ams.service.DMSService;
import com.iplant.ams.service.basicenum.dms.scada.DMSDataClass;
import com.iplant.ams.service.po.dms.scada.para.DMSDeviceRealParameter;
import com.iplant.base.controller.BaseController;
import com.iplant.base.po.ServiceResult;
import com.iplant.base.utils.RetCode;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.serializer.CloneTool;
import com.iplant.basic.service.po.bms.BMSEmployee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/DMSDeviceRealParameter")
public class DMSDeviceRealParameterController extends BaseController {

    public DMSDeviceRealParameterController() {
        super();
    }

    @Autowired
    DMSService mDMSService;


    @GetMapping("/All")
    public Object All(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            String wName = StringUtils.parseString(request.getParameter("Name"));
            List<String> wVariableName = StringUtils.splitList(request.getParameter("VariableName"), ",");
            int wDeviceID = StringUtils.parseInt(request.getParameter("DeviceID"), -1);
            int wAreaID = StringUtils.parseInt(request.getParameter("AreaID"), -1);
            String wAssetNo = StringUtils.parseString(request.getParameter("AssetNo"));
            int wDataType = StringUtils.parseInt(request.getParameter("DataType"), -1);
            int wDataClass = StringUtils.parseInt(request.getParameter("DataClass"), -1);

            int wPositionID = StringUtils.parseInt(request.getParameter("PositionID"), -1);

            ServiceResult<List<DMSDeviceRealParameter>> wServiceResult = mDMSService.DMS_SelectDeviceRealParameterList(wBMSEmployee, wName, wVariableName,
                    wAreaID, wDeviceID, wAssetNo, wDataType, wDataClass, wPositionID);
            List<DMSDeviceRealParameter> wServerRst = wServiceResult.getResult();

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServerRst, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode(), wServerRst, null);
            }
        } catch (Exception ex) {
            log.error("All", ex);
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.getMessage());
        }
        return wResult;
    }

    @GetMapping("/DeviceRecord")
    public Object DeviceRecord(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            String wDeviceCode = StringUtils.parseString(request.getParameter("DeviceCode"));
            Calendar wStartTime = StringUtils.parseCalendar(request.getParameter("StartTime"));

            Calendar wEndTime = StringUtils.parseCalendar(request.getParameter("EndTime"));

            ServiceResult<List<Map<String, Object>>> wServiceResult = mDMSService.DMS_SelectProcessRecordParams(wBMSEmployee, wDeviceCode, wStartTime, wEndTime);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServiceResult.getResult(), null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode(), wServiceResult.getResult(), null);
            }
        } catch (Exception ex) {
            log.error("DeviceRecord", ex);
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.getMessage());
        }
        return wResult;
    }


    @GetMapping("/StructAll")
    public Object StructAll(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            String wName = StringUtils.parseString(request.getParameter("Name"));
            List<String> wVariableName = StringUtils.splitList(request.getParameter("VariableName"), ",");

            int wAreaID = StringUtils.parseInt(request.getParameter("AreaID"), -1);
            int wDeviceID = StringUtils.parseInt(request.getParameter("DeviceID"), -1);
            String wAssetNo = StringUtils.parseString(request.getParameter("AssetNo"));
            int wDataType = StringUtils.parseInt(request.getParameter("DataType"), -1);
            int wDataClass = StringUtils.parseInt(request.getParameter("DataClass"), -1);
            int wPositionID = StringUtils.parseInt(request.getParameter("PositionID"), -1);


            ServiceResult<Map<Integer, Map<String, Object>>> wServiceResult = mDMSService.DMS_SelectDeviceRealParameterStructList(wBMSEmployee, wName, wVariableName,
                    wAreaID, wDeviceID, wAssetNo, wDataType, wDataClass, wPositionID);
            Map<String, Map<String, Object>> wServiceRst = new HashMap<>();
            if (wServiceResult != null && wServiceResult.Result != null && wServiceResult.Result.size() > 0) {
                for (Integer integer : wServiceResult.Result.keySet()) {
                    wServiceRst.put(integer + "", wServiceResult.Result.get(integer));
                }
            }

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceRst);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode(), null, wServiceRst);
            }
        } catch (Exception ex) {
            log.error("StructAll", ex);
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.getMessage());
        }
        return wResult;
    }


    @GetMapping("/PositionAll")
    public Object PositionAll(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            int wLineID = StringUtils.parseInt(request.getParameter("LineID"));

            int wAreaID = StringUtils.parseInt(request.getParameter("AreaID"));

            ServiceResult<List<DMSDeviceRealParameter>> wServiceResult = mDMSService.DMS_SelectDeviceRealParameterList(wBMSEmployee, "", null,
                    wAreaID, -1, "", -1, (DMSDataClass.PositionData.getValue()), -1);


            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {

                Map<String, List<DMSDeviceRealParameter>> wDMSDeviceRealParameterListDic = new HashMap<String, List<DMSDeviceRealParameter>>();

                for (DMSDeviceRealParameter wDMSDeviceRealParameter : wServiceResult.Result) {
                    List<String> wAssetNos = StringUtils.splitListRegx(wDMSDeviceRealParameter.ParameterDesc, "[\\_\\,\\;\\s\\\\]");

                    for (String wAssetNo : wAssetNos) {
                        if (StringUtils.isNotEmpty(wAssetNo) && StringUtils.parseInt(wAssetNo) > 0) {

                            if (!wDMSDeviceRealParameterListDic.containsKey(wAssetNo))
                                wDMSDeviceRealParameterListDic.put(wAssetNo, new ArrayList<DMSDeviceRealParameter>());

                            wDMSDeviceRealParameterListDic.get(wAssetNo).add(wDMSDeviceRealParameter);
                        }
                    }
                }
                Map<String, Object> wDictionary = new HashMap<String, Object>();

                Map<String, Object> wObject;
                for (String wAssetNo : wDMSDeviceRealParameterListDic.keySet()) {
                    wObject = new HashMap<>();
                    wObject.put("AssetNo", wAssetNo);
                    wObject.put("TotalCount", wDMSDeviceRealParameterListDic.get(wAssetNo).size());
                    wObject.put("PositionList", wDMSDeviceRealParameterListDic.get(wAssetNo).stream().collect(Collectors.groupingBy(p -> p.PositionName)));
                    wObject.put("PositionCount", wDMSDeviceRealParameterListDic.get(wAssetNo).stream().collect(Collectors.groupingBy(p -> p.PositionName,
                            Collectors.summingInt(q -> StringUtils.isNotEmpty(q.ParameterValue) ? 1 : 0))));

                    wDictionary.put(wAssetNo, wObject);
                }

                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wDictionary);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode());
            }
        } catch (Exception ex) {
            log.error("PositionAll", ex);
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.getMessage());
        }
        return wResult;
    }


    @GetMapping("/DeviceCurrentAll")
    public Object DeviceCurrentAll(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            int wDeviceID = StringUtils.parseInt(request.getParameter("DeviceID"), -1);
            String wDeviceNo = StringUtils.parseString(request.getParameter("DeviceNo"));
            String wAssetNo = StringUtils.parseString(request.getParameter("AssetNo"));


            ServiceResult<Map<String, Object>> wServiceResult = mDMSService.DMS_SelectDeviceCurrentStruct(wBMSEmployee,

                    wDeviceID, wDeviceNo, wAssetNo);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode(), null, wServiceResult.Result);
            }
        } catch (Exception ex) {
            log.error("DeviceCurrentAll", ex);
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.getMessage());
        }
        return wResult;
    }


    @GetMapping("/Info")
    public Object Info(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {

            BMSEmployee wBMSEmployee = GetSession(request);

            int wID = StringUtils.parseInt(request.getParameter("ID"), -1);
            String wDeviceNo = StringUtils.parseString(request.getParameter("DeviceNo"));


            ServiceResult<DMSDeviceRealParameter> wServiceResult = mDMSService.DMS_SelectDeviceRealParameter(wBMSEmployee, wID,
                    wDeviceNo);

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", null, wServiceResult.Result);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode(), null, wServiceResult.Result);
            }
        } catch (Exception ex) {
            log.error("Info", ex);
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.getMessage());
        }
        return wResult;
    }

    @GetMapping("/DeviceAll")
    public Object DeviceAll(HttpServletRequest request) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wBMSEmployee = GetSession(request);

            List<Integer> wIDList = StringUtils.parseIntList(request.getParameter("DeviceIDList"), ",");

            ServiceResult<List<DMSDeviceRealParameter>> wServiceResult = mDMSService.DMS_SelectDeviceRealParameterList(wBMSEmployee,
                    wIDList);
            List<DMSDeviceRealParameter> wServerRst = wServiceResult.getResult();

            if (StringUtils.isEmpty(wServiceResult.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServerRst, null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServiceResult.getFaultCode(), wServerRst, null);
            }
        } catch (Exception ex) {
            log.error("DeviceAll", ex);
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.getMessage());
        }
        return wResult;
    }

    @PostMapping("/SyncRealParameter")
    public Object SyncRealParameter(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {
            BMSEmployee wBMSEmployee = GetSession(request);
            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            List<DMSDeviceRealParameter> wDMSDeviceRealParameterList = CloneTool.CloneArray(wParam.get("data"), DMSDeviceRealParameter.class);
            ServiceResult<List<String>> wServerRst = mDMSService.DMS_SyncDeviceRealParameterList(wBMSEmployee, wDMSDeviceRealParameterList);
            // 直接更新数据库值 没有则插入
            if (StringUtils.isEmpty(wServerRst.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServerRst.getResult(), null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServerRst.getFaultCode(), wServerRst.getResult(), null);
            }
        } catch (Exception ex) {
            log.error("SyncRealParameter", ex);
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.getMessage());
        }
        return wResult;

    }


    @PostMapping("/SyncProcessRecord")
    public Object SyncProcessRecord(HttpServletRequest request, @RequestBody Map<String, Object> wParam) {
        Map<String, Object> wResult = new HashMap<String, Object>();
        try {


            BMSEmployee wBMSEmployee = GetSession(request);
            if (!wParam.containsKey("data")) {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, RetCode.SERVER_RST_ERROR_OUT);
                return wResult;
            }

            List<DMSDeviceRealParameter> wDMSDeviceRealParameterList = CloneTool.CloneArray(wParam.get("data"), DMSDeviceRealParameter.class);
            ServiceResult<List<String>> wServerRst = mDMSService.DMS_SyncDeviceRealParameterList(wBMSEmployee, wDMSDeviceRealParameterList);
            // 直接更新数据库值 没有则插入
            if (StringUtils.isEmpty(wServerRst.getFaultCode())) {
                wResult = GetResult(RetCode.SERVER_CODE_SUC, "", wServerRst.getResult(), null);
            } else {
                wResult = GetResult(RetCode.SERVER_CODE_ERR, wServerRst.getFaultCode(), wServerRst.getResult(), null);
            }
        } catch (Exception ex) {
            log.error("SyncProcessRecord", ex);
            wResult = GetResult(RetCode.SERVER_CODE_ERR, ex.getMessage());
        }
        return wResult;

    }


}
